from django.template import loader
from django.conf import settings

from contents.models import ContentCategory
import os

from goods.utils import get_categories


def generate_static_index_html():
    # 分类查询
    categories = get_categories()

    # 查询广告
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 生成html
    context = {
        'categories': categories,
        'contents': contents
    }
    template = loader.get_template('index.html')

    html_text = template.render(context)

    # 保存html文件
    html_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')

    with open(html_path, 'w', encoding='utf-8') as f:
        f.write(html_text)
